package org.jdk.learning.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/**
 * @author xin
 * @version 1.0
 */
public class ProducerConsumerDemo {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        final ShareResource resource = new ShareResource(2);
        executorService.submit(() -> IntStream.range(0, 10).forEach(i -> resource.add(new Random().nextInt(100))));
        executorService.submit(() -> IntStream.range(0, 10).forEach(i -> resource.remove()));

        executorService.shutdown();
    }
}


class ShareResource {

    private List<Integer> datas;

    private Integer len;

    private Lock lock;

    private Condition notFull;

    private Condition notEmpty;


    ShareResource(int len) {
        this.len = len;
        this.datas = new ArrayList<>(len);
        this.lock = new ReentrantLock();
        this.notFull = lock.newCondition();
        this.notEmpty = lock.newCondition();
    }


    void add(Integer data) {
        lock.lock(); //acquire lock

        try {
            if (datas.size() == len) { //full
                notFull.await();
            }
            //insert data
            datas.add(data);
            System.out.println("生产数据：" + data);
            notEmpty.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); // release lock
        }

        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void remove() {
        lock.lock();

        try {
            if (datas.size() == 0) {
                notEmpty.await();
            }
            Integer data = datas.remove(0);
            System.out.println("消费数据: " + data);
            notFull.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
